package com.woniu.aimd.controller; // 请替换为您的 Controller 包名

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.util.SaResult;
import com.woniu.aimd.config.ai.test.SpringAIChatClient;
import com.woniu.aimd.config.ai.test.SpringAIChatClientTest;
import com.woniu.aimd.pojo.entity.ChatRequest; // 导入您的 ChatRequest DTO
// import com.woniu.aimd.service.AIService; // 如果您有这个服务
import com.woniu.aimd.pojo.entity.ChatRequestDTO;
import com.woniu.aimd.prompt.AiDialogPrompt;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

// import org.springframework.ai.chat.client.ChatClient; // 移除了未使用的导入，除非 chatClientConfig 类型是这个

@RestController
@RequestMapping("/chat_t") // 假设您的基础路径是 /api/chat
public class AiChatControllerTest {



    private final SpringAIChatClientTest chatClient;
    // 通过构造器注入
    @Autowired // 确保 Spring 可以找到并注入 SpringAIChatClient
    public AiChatControllerTest(SpringAIChatClientTest chatClient) {
        this.chatClient = chatClient;
    }

    /**
     * @Description: 返回文本流(SSE格式), 接收POST请求体中的JSON数据
     * @return: Flux<String>
     * @Author: zcnovice (modified)
     * @date: 2025/6/12
     */
//    @SaCheckPermission("ai")
//    @PostMapping(value = "/stream_t", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> streamChat(@RequestBody ChatRequest chatRequest) {
//        String message = chatRequest.getMessage();
//        String model = chatRequest.getModel();
//        //当前文章上下文
//
//        //打印消息
//        System.out.println("Received message: " + message);
//        // 日志记录收到的请求和模型
//        System.out.println("Received streaming request for model: " + model + ", message: " + message.substring(0, Math.min(message.length(), 50)) + "...");
//        // 调用更新后的 streamChat 方法，传递 message 和 model
//        return chatClient.streamChat(message, model)
//                .map(content -> {
//                    String formattedContent = content.replace("\n", "\\n"); // 转换为可见换行符
//                    // 确保换行符被正确包装在 SSE 中
//                    return ServerSentEvent.<String>builder()
//                            .data(formattedContent)
//                            .build();
//                })
//                .onErrorResume(error -> {
//                    System.err.println("Stream error: " + error.getMessage());
//                    return Flux.just(ServerSentEvent.<String>builder()
//                            .data("错误：" + error.getMessage())
//                            .build());
//                });
//
//    }


    @SaCheckPermission("ai")
    @PostMapping(value = "/stream_t", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChat2(@RequestBody ChatRequestDTO chatRequest) {

        System.out.println("content"+chatRequest.getContent());
        System.out.println("userput"+chatRequest.getMessage());
        // 调用更新后的 streamChat 方法，传递 message 和 model
        return chatClient.streamChat2(chatRequest)
                .map(content -> {
                    String formattedContent = content.replace("\n", "\\n"); // 转换为可见换行符
                    // 确保换行符被正确包装在 SSE 中
                    return ServerSentEvent.<String>builder()
                            .data(formattedContent)
                            .build();
                })
                .onErrorResume(error -> {
                    System.err.println("Stream error: " + error.getMessage());
                    return Flux.just(ServerSentEvent.<String>builder()
                            .data("错误：" + error.getMessage())
                            .build());
                });
    }
//    @PutMapping("getNode")
//    public String getNode(@RequestBody String title){
//        return chatClient
//    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/delete/{userId}")
    public SaResult deleteConversation(@PathVariable String userId) {
        try {
            redisTemplate.delete(ChatMemory.CONVERSATION_ID+userId);
        } catch (Exception e) {
            return SaResult.error("删除失败");
        }
         return  SaResult.ok("删除成功");
    }


}